package com.biao.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biao.common.utils.PageUtils;
import com.biao.common.utils.Query;
import com.biao.mall.product.dao.CategoryDao;
import com.biao.mall.product.entity.CategoryEntity;
import com.biao.mall.product.service.CategoryBrandRelationService;
import com.biao.mall.product.service.CategoryService;
import com.biao.mall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private RedissonClient redisson;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1查询所有数据
        List<CategoryEntity> list = this.list();
        //2找到根节点
        //获取父节点
        List<CategoryEntity> RootNodes = new ArrayList<>();
        for (CategoryEntity categoryEntity : list) {
            if (categoryEntity.getParentCid() == 0) {
                RootNodes.add(categoryEntity);
            }
        }
        //建立树形结构
        List<CategoryEntity> treeMenus = new ArrayList<>();
        for (CategoryEntity menuNode : RootNodes) {
            menuNode = buildChilTree(menuNode, list);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO检查当前删除的菜单，是否被别的地方引用
        this.removeByIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }

    private CategoryEntity buildChilTree(CategoryEntity pNode, List<CategoryEntity> all) {
        List<CategoryEntity> chilMenus = new ArrayList<>();
        for (CategoryEntity menuNode : all) {
            if (menuNode.getParentCid().equals(pNode.getCatId())) {
                chilMenus.add(buildChilTree(menuNode, all));
            }
        }
        pNode.setChildren(chilMenus);
        return pNode;

    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        updateById(category);
        if (!StringUtils.isBlank(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {

        LambdaQueryWrapper<CategoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryEntity::getParentCid, 0);
        List<CategoryEntity> categoryEntities = baseMapper.selectList(queryWrapper);
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        RLock lock = redisson.getLock("getCatelogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> cateLogJsonDB = null;
        try {
            cateLogJsonDB = getCateLogJsonDB();
        } finally {
            lock.unlock();
        }
        return cateLogJsonDB;
    }

    private Map<String, List<Catelog2Vo>> getCateLogJsonDB() {

        String data = redisTemplate.opsForValue().get("cateLogJsonDB");
        if (!StringUtils.isBlank(data)) {
            Map<String, List<Catelog2Vo>> listMap = JSON.parseObject(data, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return listMap;
        }
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_Cid(categoryEntities, 0L);
        Map<String, List<Catelog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> leve2s = getParent_Cid(categoryEntities, v.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (leve2s != null) {
                catelog2VoList = leve2s.stream().map(leve2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    List<CategoryEntity> leve3s = getParent_Cid(categoryEntities, leve2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                    if (leve3s != null) {
                        catelog3Vos = leve3s.stream().map(leve3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setId(leve3.getCatId().toString());
                            catelog3Vo.setCatalog2Id(leve2.getCatId().toString());
                            catelog3Vo.setName(leve3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }

                    catelog2Vo.setCatalog3List(catelog3Vos);
                    catelog2Vo.setCatalog1Id(v.getParentCid().toString());
                    catelog2Vo.setId(leve2.getCatId().toString());
                    catelog2Vo.setName(leve2.getName());
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));

        String jsonString = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("cateLogJsonDB", jsonString);
        return map;
    }

    private List<CategoryEntity> getParent_Cid(List<CategoryEntity> list, Long parentId) {
        return list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == parentId).collect(Collectors.toList());
    }

}



